package com.example.demo.service.impl;

import com.example.demo.dao.SysRoleDao;
import com.example.demo.entity.SysRole;
import com.example.demo.service.PermissionService;
import com.example.demo.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @className wuyp
 * @description:
 * @Date 2022/3/25 10:30
 **/
@Service
@Transactional(rollbackOn = Exception.class )
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private PermissionService permissionService;
    @Override
    public List<SysRole> findAll() {

        return sysRoleDao.findAll();
    }

    @Override
    public List<SysRole> findAllById(List<Integer> ids) {
        return sysRoleDao.findAllById(ids);
    }

    @Override
    public void addRole(SysRole sysRole) {
        sysRoleDao.save(sysRole);
    }

    @Override
    public void deleteRole(Integer id) {
        sysRoleDao.deleteById(id);
    }

    @Override
    public SysRole findById(Integer id) {
        return sysRoleDao.findById(id).get();
    }

    @Override
    public void updateRole(SysRole sysRole) {
        sysRoleDao.saveAndFlush(sysRole);
        sysRoleDao.flush();
    }

    @Override
    public List<SysRole> findRoleByName(String roleName) {
        SysRole role =new SysRole();
        role.setName(roleName);
        Example<SysRole> roleExample =Example.of(role);
        return sysRoleDao.findAll(roleExample);
    }

    @Override
    public List<Integer> getRoleIdsByName(String roleName) {
        SysRole role =new SysRole();
        role.setName(roleName);
        Example<SysRole> roleExample =Example.of(role);
       List<SysRole>roles= sysRoleDao.findAll(roleExample);
       List<Integer>ids =new ArrayList<>();
       for (SysRole rr:roles){
           ids.add(rr.getId());
       }
        return ids;
    }

    @Override
    public void deleteBatchRoles(List<Integer>ids) {
        //删除角色信息
        sysRoleDao.deleteAllByIdInBatch(ids);
        //对应的角色菜单也要删除
        for (Integer id:ids){
            permissionService.deleteByRoleId(id);
        }
    }
}
